package logic

import (
	"fmt"
	"gvb-server/Request"
	"gvb-server/global"
	"gvb-server/models"
	"gvb-server/utils"
	"strings"
)

type CheckData struct {
	models.Menu `json:"menu"`
	Bids        string `json:"-"`
}

type MenuNameList struct {
	ID        uint   `json:"id"`
	MenuTitle string `json:"title"`
	Path      string `json:"path"`
}

func (m Menu) GetMenuList(s Request.MenuRequest) (utils.RList[CheckData], error) {

	//var ad []models.Menu
	//w := map[string]any{
	//	"status": 1,
	//}
	//sort := "create_date asc"
	//if s.Sort == "" {
	//	sort = "create_date desc"
	//}

	//err = global.DB.Order(sort).Where(w).Find(&ad).Error	// 使用model去查询 自动会去关联这个结构体 使用外建
	//ids := utils.GetStructValByColumnUint(ad, "ID")
	//fmt.Printf("获取到的ids：%v\n", ids)

	// 获取资源
	var rb utils.RList[CheckData]
	var CheckData []CheckData

	query := global.DB.Table("menus as a")
	query.Joins("left join menu_banners as b ON a.id = b.menu_id").Group("b.menu_id,a.id").Select("a.*,GROUP_CONCAT(b.banner_id ORDER BY b.banner_id ASC SEPARATOR ',') AS Bids")
	err = query.Scan(&CheckData).Error
	//fmt.Printf("CheckData: %#v\n", CheckData )
	for k, datum := range CheckData {
		bids := strings.Split(datum.Bids, ",")
		err = global.DB.Table("banners").Where("id in ?", bids).Scan(&CheckData[k].Banners).Error
	}

	fmt.Printf("checkData: %#v\n", CheckData)

	rb.List = CheckData
	rb.Page = s.Page
	rb.Size = s.Size
	rb.TotalPages = totalPages
	return rb, nil
}

func (m Menu) GetMenuNameList() (res utils.Response) {
	var menuNameList []MenuNameList
	err := global.DB.Table("menus").Select("id,menu_title,path").Where("status = ?", utils.STATUSNORMAL).Scan(&menuNameList).Error
	if err != nil {
		res.Code = utils.ERROR
		res.Msg = err.Error()
		return
	}
	res.Code = utils.SUCCESS
	res.Msg = "获取成功"
	res.Data = menuNameList
	return
}

func (m Menu) DelMenu(s Request.MenuDelRequest) (Pub utils.PubStatus) {
	models.MenuDelByIds(s)
	Pub.Status = utils.SUCCESS
	Pub.Msg = "删除成功"
	return
}

// CreateMenu 修改文件
func (m Menu) CreateMenu(s Request.MenuCreateRequest) (Pub utils.PubStatus) {
	if len(s.ImageSortList) == 0 {
		Pub.Msg = "添加失败，图片必须"
		return
	}
	Pub = models.MenuCreateData(s)
	return
}

// UpdateMenu 修改文件
func (m Menu) UpdateMenu(s Request.MenuCreateRequest) (Pub utils.PubStatus) {
	models.MenuCreateData(s)
	Pub.Status = utils.SUCCESS
	Pub.Msg = "修改成功"
	return
}
